{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 微软与百度智能云代码调用情况（含微软人脸寻找相似度API、人脸检测API、人脸数据库API，百度智能云人脸比对API，活体检测API)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 微软\n",
    "- 人脸数据库api\n",
    "- 人脸检测api\n",
    "- 人脸杜比api"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 导入模块\n",
    "import requests \n",
    "import json\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 创建人脸数据库列表"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1、create 我们创建了一个空的列表放在云空间上，并对列表的相关内容进行了解释\n",
    "create_facelists_url = \"https://faces-recognition.cognitiveservices.azure.com/face/v1.0/facelists/{faceListId}\" \n",
    "subscription_key = \"密钥\"\n",
    "assert subscription_key\n",
    "headers = {\n",
    "    # Request headers\n",
    "    'Content-Type': 'application/json',\n",
    "    'Ocp-Apim-Subscription-Key': subscription_key,\n",
    "}\n",
    "data = {\n",
    "    \"name\": \"about_sherlock_holmes\",  # 坑：name大写报错\n",
    "    \"userData\": \"关于神探夏洛克的shelock的剧照\",\n",
    "    \"recognitionModel\": \"recognition_02\"  # 选择第二种模型\n",
    "}\n",
    "params = {\n",
    "    # Request parameters    \n",
    "   \n",
    "    \"faceListId\":\"about_sherlock_holmes_list\" # 坑：faceListId大写报错 \n",
    "       # faceListId 虽然和data里面的参数一样是参数，但是必须单独放置，区分与另外一组参数\n",
    "#     'detectionModel': 'detection_01',\n",
    "}\n",
    "\n",
    "r_create = requests.put(create_facelists_url,headers=headers,params=params,json=data)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "200"
      ]
     },
     "execution_count": 33,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 返回状态码信息\n",
    "r_create.status_code"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "b''"
      ]
     },
     "execution_count": 28,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "r_create.content"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Add face 添加10张以上的face图片作为对比数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<Response [200]>"
      ]
     },
     "execution_count": 63,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 2、Add face 这里我们开始匹配上一步代码创建列表的 id 与 图片 id\n",
    "add_face_url =\"https://faces-recognition.cognitiveservices.azure.com/face/v1.0/facelists/{faceListId}/persistedFaces\"\n",
    "\n",
    "# 坑 注意图片的脸只有一个\n",
    "img_url = \"https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=2047204023,686597329&fm=26&gp=0.jpg\"\n",
    "\n",
    "params_add_face={\n",
    "    \n",
    "    \"faceListId\":\"about_sherlock_holmes_list\"  # 指定了 id 给 yong_shelton_list的列表\n",
    "}    \n",
    "\n",
    "r_add_face = requests.post(add_face_url,headers=headers,params=params_add_face,json={\"url\":img_url})\n",
    "r_add_face\n",
    "# r = requests.post(add_face, headers=headers,params = params,json={\"url\": add_face_image})\n",
    "# r.status_code"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "b'{\"persistedFaceId\":\"a858e6b7-6641-4853-8305-347a666a192a\"}'"
      ]
     },
     "execution_count": 51,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "r_add_face.content"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 人脸检测API:Detect 检测需要检测的人脸获取faceid"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'[{\"faceId\": \"cee53c83-5406-47b2-83ed-f8684bad0442\", \"faceRectangle\": {\"top\": 54, \"left\": 242, \"width\": 97, \"height\": 97}, \"faceAttributes\": {\"smile\": 0.0, \"headPose\": {\"pitch\": 4.4, \"roll\": -1.8, \"yaw\": -4.6}, \"gender\": \"male\", \"age\": 35.0, \"facialHair\": {\"moustache\": 0.1, \"beard\": 0.1, \"sideburns\": 0.1}, \"glasses\": \"NoGlasses\", \"emotion\": {\"anger\": 0.002, \"contempt\": 0.001, \"disgust\": 0.0, \"fear\": 0.0, \"happiness\": 0.0, \"neutral\": 0.997, \"sadness\": 0.0, \"surprise\": 0.0}, \"blur\": {\"blurLevel\": \"medium\", \"value\": 0.45}, \"exposure\": {\"exposureLevel\": \"goodExposure\", \"value\": 0.61}, \"noise\": {\"noiseLevel\": \"low\", \"value\": 0.22}, \"makeup\": {\"eyeMakeup\": false, \"lipMakeup\": false}, \"accessories\": [], \"occlusion\": {\"foreheadOccluded\": false, \"eyeOccluded\": false, \"mouthOccluded\": false}, \"hair\": {\"bald\": 0.02, \"invisible\": false, \"hairColor\": [{\"color\": \"black\", \"confidence\": 0.98}, {\"color\": \"brown\", \"confidence\": 0.95}, {\"color\": \"gray\", \"confidence\": 0.44}, {\"color\": \"other\", \"confidence\": 0.27}, {\"color\": \"red\", \"confidence\": 0.08}, {\"color\": \"blond\", \"confidence\": 0.03}]}}}]'"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 3、检测人脸的faceid\n",
    "\n",
    "\n",
    "# replace <My Endpoint String> with the string from your endpoint URL\n",
    "face_api_url = 'https://faces-recognition.cognitiveservices.azure.com/face/v1.0/detect'\n",
    "\n",
    "# 请求正文\n",
    "image_url = 'https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=3007274582,3781337334&fm=26&gp=0.jpg'\n",
    "\n",
    "headers = {'Ocp-Apim-Subscription-Key': subscription_key}\n",
    "\n",
    "# 请求参数\n",
    "params = {\n",
    "    'returnFaceId': 'true',\n",
    "    'returnFaceLandmarks': 'false',\n",
    "    # 选择model\n",
    "    'recognitionModel':'recognition_02',\n",
    "    'detectionModel':'detection_01',\n",
    "    # 可选参数,请仔细阅读API文档\n",
    "    'returnFaceAttributes': 'age,gender,headPose,smile,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure,noise',\n",
    "}\n",
    "\n",
    "response = requests.post(face_api_url, params=params,\n",
    "                         headers=headers, json={\"url\": image_url})\n",
    "# json.dumps 将json--->字符串\n",
    "json.dumps(response.json())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 寻找相似度API: find similars 返回相似置信度"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 4、寻找相似性\n",
    "\n",
    "findsimilars_url = \"https://faces-recognition.cognitiveservices.azure.com/face/v1.0/findsimilars\"\n",
    "\n",
    "# 请求正文 faceId需要先检测一张照片获取\n",
    "data_findsimilars = {\n",
    "    \"faceId\":\"cee53c83-5406-47b2-83ed-f8684bad0442\",\n",
    "    \"faceListId\":\"about_sherlock_holmes_list\",\n",
    "    \"maxNumOfCandidatesReturned\": 10,\n",
    "    \"mode\": \"matchPerson\"\n",
    "    }\n",
    "\n",
    "r_findsimilars = requests.post(findsimilars_url,headers=headers,json=data_findsimilars)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "200"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "r_findsimilars.status_code"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "b'[{\"persistedFaceId\":\"c5fade00-1378-4f33-92ca-4aa782f2eb82\",\"confidence\":1.0},{\"persistedFaceId\":\"a858e6b7-6641-4853-8305-347a666a192a\",\"confidence\":0.94714},{\"persistedFaceId\":\"54d848f5-9af1-46b8-906d-fc79f4b9ac7b\",\"confidence\":0.94137},{\"persistedFaceId\":\"3f5972ee-6697-4fbf-ad47-447f21424be6\",\"confidence\":0.92606},{\"persistedFaceId\":\"782d2203-03e7-4735-8a95-8eafc6329d80\",\"confidence\":0.92511},{\"persistedFaceId\":\"8363e722-6642-43e4-906f-75bf2f75fb17\",\"confidence\":0.91858},{\"persistedFaceId\":\"122f6c23-4b20-4d1e-9fba-99cec00635ee\",\"confidence\":0.91761},{\"persistedFaceId\":\"62172513-0c8b-4f67-8d0d-24cd841aab5f\",\"confidence\":0.91295},{\"persistedFaceId\":\"5380ffa1-c111-41b6-b6a5-55e765838c8b\",\"confidence\":0.90518},{\"persistedFaceId\":\"6dbe57ba-a959-4b05-8b26-041f97633658\",\"confidence\":0.89717}]'"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "r_findsimilars.content"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[{'persistedFaceId': 'c5fade00-1378-4f33-92ca-4aa782f2eb82',\n",
       "  'confidence': 1.0},\n",
       " {'persistedFaceId': 'a858e6b7-6641-4853-8305-347a666a192a',\n",
       "  'confidence': 0.94714},\n",
       " {'persistedFaceId': '54d848f5-9af1-46b8-906d-fc79f4b9ac7b',\n",
       "  'confidence': 0.94137},\n",
       " {'persistedFaceId': '3f5972ee-6697-4fbf-ad47-447f21424be6',\n",
       "  'confidence': 0.92606},\n",
       " {'persistedFaceId': '782d2203-03e7-4735-8a95-8eafc6329d80',\n",
       "  'confidence': 0.92511},\n",
       " {'persistedFaceId': '8363e722-6642-43e4-906f-75bf2f75fb17',\n",
       "  'confidence': 0.91858},\n",
       " {'persistedFaceId': '122f6c23-4b20-4d1e-9fba-99cec00635ee',\n",
       "  'confidence': 0.91761},\n",
       " {'persistedFaceId': '62172513-0c8b-4f67-8d0d-24cd841aab5f',\n",
       "  'confidence': 0.91295},\n",
       " {'persistedFaceId': '5380ffa1-c111-41b6-b6a5-55e765838c8b',\n",
       "  'confidence': 0.90518},\n",
       " {'persistedFaceId': '6dbe57ba-a959-4b05-8b26-041f97633658',\n",
       "  'confidence': 0.89717}]"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a = [{\"persistedFaceId\":\"c5fade00-1378-4f33-92ca-4aa782f2eb82\",\"confidence\":1.0},{\"persistedFaceId\":\"a858e6b7-6641-4853-8305-347a666a192a\",\"confidence\":0.94714},{\"persistedFaceId\":\"54d848f5-9af1-46b8-906d-fc79f4b9ac7b\",\"confidence\":0.94137},{\"persistedFaceId\":\"3f5972ee-6697-4fbf-ad47-447f21424be6\",\"confidence\":0.92606},{\"persistedFaceId\":\"782d2203-03e7-4735-8a95-8eafc6329d80\",\"confidence\":0.92511},{\"persistedFaceId\":\"8363e722-6642-43e4-906f-75bf2f75fb17\",\"confidence\":0.91858},{\"persistedFaceId\":\"122f6c23-4b20-4d1e-9fba-99cec00635ee\",\"confidence\":0.91761},{\"persistedFaceId\":\"62172513-0c8b-4f67-8d0d-24cd841aab5f\",\"confidence\":0.91295},{\"persistedFaceId\":\"5380ffa1-c111-41b6-b6a5-55e765838c8b\",\"confidence\":0.90518},{\"persistedFaceId\":\"6dbe57ba-a959-4b05-8b26-041f97633658\",\"confidence\":0.89717}]\n",
    "a"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## get查看facelist中的信息"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 5、Get facelist\n",
    "get_facelist_url = \"https://faces-recognition.cognitiveservices.azure.com/face/v1.0/facelists/{faceListId}\"\n",
    "\n",
    "data = {\n",
    "    \"faceListId\":\"about_sherlock_holmes_list\",\n",
    "\n",
    "}\n",
    "\n",
    "r_get_facelist = requests.get(get_facelist_url,headers=headers,params=data)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "200"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "r_get_facelist.status_code"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'persistedFaces': [{'persistedFaceId': '72c62f96-46e2-4b73-bece-fe57522a85f2',\n",
       "   'userData': None},\n",
       "  {'persistedFaceId': 'ad6d4273-e263-4132-b953-868afe5a1b69',\n",
       "   'userData': None},\n",
       "  {'persistedFaceId': '122f6c23-4b20-4d1e-9fba-99cec00635ee',\n",
       "   'userData': None},\n",
       "  {'persistedFaceId': '54d848f5-9af1-46b8-906d-fc79f4b9ac7b',\n",
       "   'userData': None},\n",
       "  {'persistedFaceId': '3f5972ee-6697-4fbf-ad47-447f21424be6',\n",
       "   'userData': None},\n",
       "  {'persistedFaceId': '6dbe57ba-a959-4b05-8b26-041f97633658',\n",
       "   'userData': None},\n",
       "  {'persistedFaceId': '782d2203-03e7-4735-8a95-8eafc6329d80',\n",
       "   'userData': None},\n",
       "  {'persistedFaceId': '62172513-0c8b-4f67-8d0d-24cd841aab5f',\n",
       "   'userData': None},\n",
       "  {'persistedFaceId': '8363e722-6642-43e4-906f-75bf2f75fb17',\n",
       "   'userData': None},\n",
       "  {'persistedFaceId': 'a858e6b7-6641-4853-8305-347a666a192a',\n",
       "   'userData': None},\n",
       "  {'persistedFaceId': '04ab3f19-504f-418a-8353-632b37819cd7',\n",
       "   'userData': None},\n",
       "  {'persistedFaceId': '5380ffa1-c111-41b6-b6a5-55e765838c8b',\n",
       "   'userData': None},\n",
       "  {'persistedFaceId': 'c5fade00-1378-4f33-92ca-4aa782f2eb82',\n",
       "   'userData': None},\n",
       "  {'persistedFaceId': 'db7a61a4-8f3a-48b4-a5b4-28c1cff2302c',\n",
       "   'userData': None}],\n",
       " 'faceListId': 'about_sherlock_holmes_list',\n",
       " 'name': 'about_sherlock_holmes',\n",
       " 'userData': '关于神探夏洛克的shelock的剧照'}"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "r_get_facelist.json()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 百度智能云\n",
    "- 人脸对比API\n",
    "- 活体检测API"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 百度人脸对比API调用"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "import urllib\n",
    "import ssl\n",
    "from urllib import request, parse\n",
    "import json\n",
    " \n",
    "# client_id 为官网获取的AK， client_secret 为官网获取的SK\n",
    "def get_token():\n",
    "    context = ssl._create_unverified_context()\n",
    "    host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=1S7MjtxNYGfiT7K7zyDPYoZN&client_secret=密钥'\n",
    "    request = urllib.request.Request(host)\n",
    "    request.add_header('Content-Type', 'application/json; charset=UTF-8')\n",
    "    response = urllib.request.urlopen(request, context=context)\n",
    "    # 获取请求结果\n",
    "    content = response.read()\n",
    "    # 转换为字符\n",
    "    content = bytes.decode(content)\n",
    "    # 转换为字典\n",
    "    content = eval(content[:-1])\n",
    "    return content['access_token']\n",
    " \n",
    " \n",
    "# # 转换图片\n",
    "# 读取文件内容，转换为base64编码\n",
    "# 二进制方式打开图文件\n",
    "def imgdata(file1path, file2path):\n",
    "    import base64\n",
    "    f = open(r'%s' % file1path, 'rb')\n",
    "    pic1 = base64.b64encode(f.read())\n",
    "    f.close()\n",
    "    f = open(r'%s' % file2path, 'rb')\n",
    "    pic2 = base64.b64encode(f.read())\n",
    "    f.close()\n",
    "    # 将图片信息格式化为可提交信息，这里需要注意str参数设置\n",
    "    params = json.dumps(\n",
    "        [{\"image\": str(pic1, 'utf-8'), \"image_type\": \"BASE64\", \"face_type\": \"LIVE\", \"quality_control\": \"LOW\"},\n",
    "         {\"image\": str(pic2, 'utf-8'), \"image_type\": \"BASE64\", \"face_type\": \"IDCARD\", \"quality_control\": \"LOW\"}]\n",
    "    )\n",
    "    return params.encode(encoding='UTF8')\n",
    " \n",
    " \n",
    "# # 进行对比获得结果\n",
    "def img(file1path, file2path):\n",
    "    token = get_token()\n",
    "    # 人脸识别API\n",
    "    # url = 'https://aip.baidubce.com/rest/2.0/face/v3/detect?access_token='+token\n",
    "    # 人脸对比API\n",
    "    context = ssl._create_unverified_context()\n",
    "    # url = 'https://aip.baidubce.com/rest/2.0/face/v3/match?access_token=' + token\n",
    "    params = imgdata(file1path, file2path)\n",
    " \n",
    "    request_url = \"https://aip.baidubce.com/rest/2.0/face/v3/match\"\n",
    "    request_url = request_url + \"?access_token=\"+ token\n",
    "    request = urllib.request.Request(url=request_url,data=params)\n",
    "    request.add_header('Content-Type', 'application/json')\n",
    "    response = urllib.request.urlopen(request ,context=context)\n",
    "    content = response.read()\n",
    "    content = eval(content)\n",
    "    # # 获得分数\n",
    "    score = content['result']['score']\n",
    "    if score > 80:\n",
    "   \n",
    "        return '照片相似度：' + str(score) + ',同一个人'\n",
    "    else:\n",
    "    \n",
    "        return '照片相似度：' + str(score) + ',不是同一个人'\n",
    "       \n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 74,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "照片相似度：97.75167847,同一个人\n",
      "照片相似度：93.80686951,同一个人\n",
      "照片相似度：93.6815033,同一个人\n",
      "照片相似度：94.32694244,同一个人\n",
      "照片相似度：93.30691528,同一个人\n",
      "照片相似度：93.58383179,同一个人\n",
      "照片相似度：93.50257111,同一个人\n",
      "照片相似度：92.59306335,同一个人\n",
      "照片相似度：94.98168945,同一个人\n",
      "照片相似度：94.82902527,同一个人\n"
     ]
    }
   ],
   "source": [
    "print(img(\"./images/夏洛克1.jpg\",\"./images/夏洛克1.jpg\"))\n",
    "print(img(\"./images/夏洛克1.jpg\",\"./images/夏洛克2.jpeg\"))\n",
    "print(img(\"./images/夏洛克1.jpg\",\"./images/夏洛克3.jpg\"))\n",
    "print(img(\"./images/夏洛克1.jpg\",\"./images/夏洛克4.jpeg\"))\n",
    "print(img(\"./images/夏洛克1.jpg\",\"./images/夏洛克5.jpeg\"))\n",
    "print(img(\"./images/夏洛克1.jpg\",\"./images/夏洛克6.png\"))\n",
    "print(img(\"./images/夏洛克1.jpg\",\"./images/夏洛克7.png\"))\n",
    "print(img(\"./images/夏洛克1.jpg\",\"./images/夏洛克8.jpg\"))\n",
    "print(img(\"./images/夏洛克1.jpg\",\"./images/夏洛克9.jpg\"))\n",
    "print(img(\"./images/夏洛克1.jpg\",\"./images/夏洛克10.jpg\"))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 百度活体检测调用\n",
    "- 基于图片的活体检测：基于单张图片，判断图片中的人脸是否为二次翻拍（举例：如用户A用手机拍摄了一张包含人脸的图片一，用户B翻拍了图片一得到了图片二，并用图片二伪造成用户A去进行识别操作，这种情况普遍发生在金融开户、实名认证等环节）以及是否为合成图攻击。此能力可用于H5场景下的一些人脸采集场景中，增加人脸注册的安全性和真实性。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'refresh_token': '25.a40c36bbfa24ae192957ad3f556bf6c7.315360000.1910696151.282335-19386409', 'expires_in': 2592000, 'session_key': '9mzdWECNKCQPnhxBIP6uvry5J16BMGwHF94xrgtcSw+zNlZa2wcBLh+wBJAj0fj72BzoiunQ/6SQM6uVlCfDKZZw8dt83A==', 'access_token': '24.c0c64d2a7a2094f6c84e30f689f23b31.2592000.1597928151.282335-19386409', 'scope': 'public brain_all_scope vis-faceverify_faceverify_h5-face-liveness vis-faceverify_FACE_V3 vis-faceverify_idl_face_merge wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test权限 vis-classify_flower lpq_开放 cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_开放Scope vis-ocr_虚拟人物助理 idl-video_虚拟人物助理', 'session_secret': '4e50bba1ab15ab36dc491fcb6d5d34df'}\n"
     ]
    }
   ],
   "source": [
    "# encoding:utf-8\n",
    "import requests \n",
    "\n",
    "# client_id 为官网获取的AK， client_secret 为官网获取的SK\n",
    "host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=1S7MjtxNYGfiT7K7zyDPYoZN&client_secret=密钥'\n",
    "response = requests.get(host)\n",
    "if response:\n",
    "    print(response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {},
   "outputs": [],
   "source": [
    "import urllib\n",
    "import ssl\n",
    "from urllib import request, parse\n",
    "import json\n",
    "import requests\n",
    "import base64\n",
    " \n",
    "# client_id 为官网获取的AK， client_secret 为官网获取的SK\n",
    "def get_token():\n",
    "    context = ssl._create_unverified_context()\n",
    "    host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=1S7MjtxNYGfiT7K7zyDPYoZN&client_secret=密钥'\n",
    "    request = urllib.request.Request(host)\n",
    "    request.add_header('Content-Type', 'application/json; charset=UTF-8')\n",
    "    response = urllib.request.urlopen(request, context=context)\n",
    "    # 获取请求结果\n",
    "    content = response.read()\n",
    "    # 转换为字符\n",
    "    content = bytes.decode(content)\n",
    "    # 转换为字典\n",
    "    content = eval(content[:-1])\n",
    "    access_token = content['access_token']\n",
    "    return access_token\n",
    "\n",
    "'''\n",
    "在线活体检测\n",
    "'''\n",
    "def alive_detection(filePath):\n",
    "    access_token = get_token()\n",
    "    request_url = \"https://aip.baidubce.com/rest/2.0/face/v3/faceverify\"\n",
    "\n",
    "    filePath=filePath#照片路径\n",
    "\n",
    "    f=open(filePath,\"rb\")\n",
    "\n",
    "    data = base64.b64encode(f.read())#编码格式，技术文档要求\n",
    "    f.close()\n",
    "\n",
    "    image=str(data,'UTF-8')\n",
    "\n",
    "\n",
    "    params = \"[{\\\"image\\\":\\\"\" + image + \"\\\",\\\"image_type\\\":\\\"BASE64\\\",\\\"face_field\\\":\\\"age,beauty,expression\\\"}]\"\n",
    "    request_url = request_url + \"?access_token=\" + access_token\n",
    "    headers = {'content-type': 'application/json'}\n",
    "    response = requests.post(request_url, data=params, headers=headers)\n",
    "    if response:\n",
    "    #     print (response.json())#返回所有数据（字典形式）\n",
    "        rest=response.json()[\"result\"][\"face_liveness\"]#返回活体分数值（0~1）\n",
    "        if rest == 1:\n",
    "            print(\"此为活体\")\n",
    "        else:\n",
    "            print(\"非活体,警告！\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 68,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "非活体,警告！\n"
     ]
    }
   ],
   "source": [
    "alive_detection(\"./images/1.jpg\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {
    "height": "calc(100% - 180px)",
    "left": "10px",
    "top": "150px",
    "width": "326.997px"
   },
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
